package com.example.martian.utils;

import com.example.martian.config.util.RedisUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.Timer;
import java.util.TimerTask;

import static com.example.martian.utils.SmsSample.*;

@Component
public class SmsMessage {

    @Autowired
    private RedisUtils redisUtils;

    public Object smsVerification(String address) {
        String random = Utils.getRandom(6);
        String testUsername = "garycloud"; //在短信宝注册的用户名
        String testPassword = "QAZmlp"; //在短信宝注册的密码
        String testPhone = address;
        String testContent = "【灰度云矿】您的验证码是" + random + ",５分钟内有效。若非本人操作请忽略此消息。"; // 注意测试时，也请带上公司简称或网站签名，发送正规内容短信。千万不要发送无意义的内容：例如 测一下、您好。否则可能会收不到
        String httpUrl = "http://api.smsbao.com/sms";
//        String httpUrl = "http://api.sms654.com/smsUTF8.aspx";
        StringBuffer httpArg = new StringBuffer();
        httpArg.append("u=").append(testUsername).append("&");
        httpArg.append("p=").append(md5(testPassword)).append("&");
        httpArg.append("m=").append(testPhone).append("&");
        httpArg.append("c=").append(encodeUrlString(testContent, "UTF-8"));
        String result = request(httpUrl, httpArg.toString());
        System.out.println(result);
//        redisUtils.setDataToCache("verificationCode" + address, random, 30000);
        return Utils.toJSON("发送成功", result, "0");
    }

    //校验验证码
    @Transactional
    public Object verifyCode(String code, String address) {
        Object uuid = redisUtils.getDataFromCache("verificationCode" + address);
        if (code.equals(uuid)) {
            Timer timer = new Timer();
            TimerTask task = new TimerTask() {
                public void run() {
                    redisUtils.clearCache("verificationCode" + address);
                }
            };
            timer.schedule(task, 5 * 60 * 1000);
            return Utils.toJSON("注册成功", null, "0");
        } else {
            return Utils.toJSON("请输入正确的验证码,验证码5分钟内有效", null, "1");
        }
    }

    public static void main(String[] args) {
        SmsMessage smsMessage = new SmsMessage();
        smsMessage.smsVerification("15775566277");
    }
}
